import React from "react";
import {
  Avatar,
  Button,
  FilledInput,
  FormControl,
  Grid,
  InputLabel,
  MenuItem,
  Paper,
  Select,
  TextField,
  Typography,
} from "@mui/material";
import { useContext } from "react";
import { TitleContext } from "../../../router";
import { Box } from "@mui/system";
import { useEffect } from "react";
import { useState } from "react";
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import { TimePicker } from "@mui/x-date-pickers/TimePicker";
import Loading from "../../../components/loading";
import { DateTimePicker } from "@mui/x-date-pickers/DateTimePicker";
import LoadingButton from "../../../components/LoadingButton";
import Stack from "@mui/material/Stack";
import Application from "./Application";
import { DesktopDatePicker } from "@mui/x-date-pickers/DesktopDatePicker";
import dayjs from "dayjs";
import { useMutation } from "@tanstack/react-query";
import { postQueryFn } from "../../../query/postQueryFn";
import { useSnackbar } from "notistack";
import { EXAMAPPLICATION_PUT_URL } from "../../../constants/url";
import { GETCOURSE_URL, GETCOURSETIME_URL } from "../../../constants/url";
import { GET_EXAM_URL } from "../../../constants/url";
import moment from "moment/moment";
import { mutateQueryFn } from "../../../query/mutateQueryFn";

const MyTitle = ({ value }) => {
  return (
    <Typography variant="h6" sx={{ marginTop: 2, marginBottom: 1 }}>
      {value}
    </Typography>
  );
};

export default function ExamApplication() {
  const nowTitle = useContext(TitleContext);
  useEffect(() => {
    nowTitle.setnowTitle(5);
  }, []);
  const [proIsFetching, setProIsFetching] = useState(false);
  const [proisSuccess, setProisSuccess] = useState(true);
  const [infoSuccess, setisSuccess] = useState(false);

  // "name": "离散数学期末考试",
  // "date": "2022-11-15",
  // "betime": "14:00",
  // "endtime": "16:00",
  // "area": "学生在线会议室"
  const [newItem, setNewItem] = useState({});
  const [course, setCourse] = useState(); //课程号id
  const [name, setName] = useState(); //考试名称
  const [area, setArea] = useState(); //考试地点
  const [date, setDate] = useState(); //考试日期
  const [betime, setBetime] = useState(); //开始时间
  const [endtime, setEndtime] = useState(); //结束时间

  //获取考试的申请信息
  const {
    data,
    isLoading: getLoading,
    mutate: getMutate,
    isSuccess: getSuccess,
  } = useMutation(["getExams"], mutateQueryFn);

  useEffect(() => {
    getMutate({ url: GET_EXAM_URL, method: "get", useToken: true });
  }, []);

  const [rows, setRows] = useState([]);
  useEffect(() => {
    if (getSuccess) {
      setRows(
        data.data.data.map((val, key) =>
          val.status !== undefined
            ? {
                id: key + 1,
                ...val,
              }
            : {}
        )
      );
    } else {
    }
  }, [data]);


  //获取所有课程 --查询id
  const {
    data: courses,
    isLoading: getLoading1,
    mutate: getMutate1,
    isSuccess: getSuccess1,
  } = useMutation(["getCourse"], mutateQueryFn);
  const {
    //考试申请
    isError: upApError,
    isLoading: upApLoading,
    isSuccess: upApSuccess,
    data: upApdata,
    mutate: upApMutate,
  } = useMutation(["examApplicationPut"], postQueryFn);

  const { enqueueSnackbar } = useSnackbar();
  const handleUploadApplication = () => {
    if (!newItem?.course) {
      enqueueSnackbar("课程号不能为空", { variant: "warning" });
      return;
    }
    if (!newItem?.name) {
      enqueueSnackbar("课程名称不能为空", { variant: "warning" });
      return;
    }
    if (!newItem?.date) {
      enqueueSnackbar("考试日期不能为空", { variant: "warning" });
      return;
    }
    if (!newItem?.betime) {
      enqueueSnackbar("考试开始时间不能为空", { variant: "warning" });
      return;
    }
    if (!newItem?.endtime) {
      enqueueSnackbar("考试结束时间不能为空", { variant: "warning" });
      return;
    }
    if (newItem.betime > newItem.endtime) {
      enqueueSnackbar("开始时间不能晚于结束时间", { variant: "warning" });
      return;
    }
    getMutate1({ url: GETCOURSE_URL, method: "get", useToken: true }); //获取课程号用于上传考试
};
useEffect(() => {
    if (getSuccess1) {
      let courseF;
      courses.data.data.map((val, key) =>
        val.courseId == newItem.course ? (courseF = val.id) : undefined
      );
      // setCourse(courseF);
      if (courseF) {
        upApMutate({
          Key: [
            EXAMAPPLICATION_PUT_URL,
            {
              params: {
                course: courseF,
              },
              useToken: true,
            },
          ],
          method: "put",
          params: {
            name: newItem.name,
            date: moment(newItem.date.toString()).format("YYYY-MM-DD"),
            betime: moment(newItem.betime.toString()).format("HH:mm"),
            endtime: moment(newItem.endtime.toString()).format("HH:mm"),
            area: newItem.area,
          },
        });
      } else {
        enqueueSnackbar("未查询到该课程,申请考试失败", { variant: "warning" });
      }
    }
  }, [getSuccess1]);
  useEffect(() => {
    if (upApSuccess) {
      if (upApdata.data.code != 0) {
        enqueueSnackbar(upApdata.data.data, { variant: "error" });
      } else {
        setNewItem({ score: 0 });
        enqueueSnackbar("提交成功", { variant: "success" });
      }
      //重新获取列表
      getMutate({ url: GET_EXAM_URL, method: "get", useToken: true });
    }
  }, [upApSuccess]);

  return (
    <LocalizationProvider dateAdapter={AdapterDayjs}>
      <Grid container spacing={2}>
        <Grid item xs={12} md={5}>
          <Paper
            elevation={2}
            sx={{ display: "flex", float: "left", width: "100%" }}
          >
            <Box
              sx={{
                marginLeft: 2,
                marginTop: 3,
                marginBottom: 5,
                display: "flex",
                float: "left",
                flexDirection: "row",
              }}
            >
              {/* 左侧部分 */}
              <Box sx={{ display: "flex", flexDirection: "column" }}>
                <Box>
                  <Typography
                    variant="h5"
                    sx={{
                      marginTop: 0,
                      marginBottom: 1,
                      marginRight: 1,
                      width: 100,
                    }}
                  >
                    考试申请
                  </Typography>
                </Box>
                <Box sx={{ marginLeft: 3, marginTop: 0 }}>
                  <MyTitle value="课程号"></MyTitle>
                  <TextField
                    label="courseId*"
                    size="small"
                    sx={{ width: 130 }}
                    onChange={(e) => {
                      setNewItem({ ...newItem, course: e.target.value });
                    }}
                    value={newItem.course}
                  />
                  <MyTitle value="考试名称"></MyTitle>
                  <TextField
                    label="name*"
                    size="small"
                    sx={{ width: 170 }}
                    value={newItem.name}
                    onChange={(e) => {
                      setNewItem({ ...newItem, name: e.target.value });
                    }}
                  />
                  <MyTitle value="考试地点"></MyTitle>
                  <TextField
                    label="location*"
                    size="small"
                    value={newItem.area}
                    sx={{ width: 170 }}
                    onChange={(e) => {
                      setNewItem({ ...newItem, area: e.target.value });
                    }}
                  />
                  <MyTitle value="设置考试日期"></MyTitle>
                  <DesktopDatePicker
                    label="date*"
                    value={newItem.date ?? null}
                    onChange={(newValue) => {
                      setNewItem({ ...newItem, date: newValue });
                    }}
                    renderInput={(params) => (
                      <TextField size="small" {...params} />
                    )}
                  />
                  <MyTitle value="设置考试开始时间"></MyTitle>
                  <TimePicker
                    ampm={false}
                    openTo="hours"
                    views={["hours", "minutes"]}
                    inputFormat="HH:mm"
                    mask="__:__"
                    label="beginTime*"
                    value={newItem.betime ?? null}
                    onChange={(newValue) => {
                      setNewItem({ ...newItem, betime: newValue });
                    }}
                    renderInput={(params) => (
                      <TextField size="small" {...params} />
                    )}
                  />
                  <MyTitle value="设置考试结束时间"></MyTitle>
                  <TimePicker
                    ampm={false}
                    openTo="hours"
                    views={["hours", "minutes"]}
                    inputFormat="HH:mm"
                    mask="__:__"
                    label="endTime*"
                    value={newItem.endtime ?? null}
                    onChange={(newValue) => {
                      setNewItem({ ...newItem, endtime: newValue });
                    }}
                    renderInput={(params) => (
                      <TextField size="small" {...params} />
                    )}
                  />
                  {/* 保存按钮 */}
                  <Box
                    sx={{
                      marginTop: 3,
                      marginLeft: 0,
                      display: "flex",
                      flexDirection: "column",
                      justifyContent: "center",
                      alignItems: "center",
                      width: "100%",
                    }}
                  >
                    <LoadingButton
                      titler={upApSuccess ? "提交成功" : "提交申请"}
                      clickr={handleUploadApplication}
                    />
                  </Box>
                </Box>
              </Box>
              {/* 右侧部分 */}
              {/* <Box sx={{display: "flex", flexDirection: "column",marginLeft: 28}}>
                    <Box>
                        <Typography variant="h6" sx={{ marginTop: 8, marginBottom: 1,marginRight: 1,width: 150}}>
                              考试时间
                        </Typography>   
                    </Box> 
                    <MyTitle value="设置考试日期"></MyTitle>
                    <DesktopDatePicker
                      label="date*"
                      value={newItem.date ?? null}
                      onChange={(newValue) => {
                        setNewItem({ ...newItem, date: newValue });
                      }}
                      renderInput={(params) => (
                        <TextField size="small" {...params} />
                      )}
                    />
                    <MyTitle value="设置考试开始时间"></MyTitle>
                    <TimePicker
                      label="beginTime*"
                      value={newItem.betime??null}
                      onChange={(newValue) => {
                        setNewItem({ ...newItem, betime: newValue });
                      }}
                      renderInput={(params) => <TextField size="small" {...params} />}
                    />
                    <MyTitle value="设置考试结束时间"></MyTitle>
                    <TimePicker
                      label="endTime*"
                      value={endtime??null}
                      onChange={(newValue) => {
                        setNewItem({ ...newItem, endtime: newValue });
                      }}
                      renderInput={(params) => <TextField size="small" {...params} />}
                    /> */}
              {/* 保存按钮 */}
              {/* <Box
                      sx={{
                        marginTop: 5,
                        marginLeft: 0,
                        display: "flex",
                        flexDirection: "column",
                        justifyContent: "center",
                        alignItems: "center",
                        width: "100%",
                      }}
                    >
                      <LoadingButton
                        titler={infoSuccess ? "保存成功" : "保存"}
                      />
                    </Box>
              </Box> */}
            </Box>
          </Paper>
        </Grid>
        <Grid item xs={12} md={7}>
          {/* 申请列表 */}
          <Application rows={rows} getLoading={getLoading} />
        </Grid>
      </Grid>
    </LocalizationProvider>
  );
}
